package cn.xscrum.vtsp.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xscrum.common.utils.DateUtils;
import cn.xscrum.vtsp.domain.*;
import cn.xscrum.vtsp.mapper.*;
import cn.xscrum.vtsp.websocket.WebSocketServlet;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.xscrum.vtsp.service.IVtspMessageService;
import cn.xscrum.common.core.text.Convert;

/**
 * 消息持久化记录Service业务层处理
 * 
 * @author xscrum
 * @date 2021-10-01
 */
@Service
public class VtspMessageServiceImpl implements IVtspMessageService 
{
    @Autowired
    private VtspMessageMapper vtspMessageMapper;

    @Autowired
    private VtspActivityMapper vtspActivityMapper;

    @Autowired
    private VtspVolunteerMapper vtspVolunteerMapper;

    @Autowired
    private VtspEnrollMapper vtspEnrollMapper;

    @Autowired
    private VtspVisualMapper vtspVisualMapper;

    @Autowired
    private VtspFeedbackMapper vtspFeedbackMapper;

    @Autowired
    private VtspAdviceMapper vtspAdviceMapper;

    @Autowired
    private VtspActivityStatisticMapper vtspActivityStatisticMapper;

    @Autowired
    private VtspVolunteerStatisticMapper vtspVolunteerStatisticMapper;

    /**
	 * 查询消息持久化记录
     * 
     * @param messageId 消息持久化记录ID
     * @return 消息持久化记录
     */
    @Override
    public VtspMessage selectVtspMessageById(Long messageId)
    {
        return vtspMessageMapper.selectVtspMessageById(messageId);
    }

    /**
	 * 查询消息持久化记录列表
     * 
     * @param vtspMessage 消息持久化记录
     * @return 消息持久化记录
     */
    @Override
    public List<VtspMessage> selectVtspMessageList(VtspMessage vtspMessage)
    {
        return vtspMessageMapper.selectVtspMessageList(vtspMessage);
    }

    public List<VtspMessage> selectVtspMessageListById(Long volunteerId) {
        return vtspMessageMapper.selectVtspMessageListById(volunteerId);
    }

    /**
	 * 新增消息持久化记录
     * 
     * @param vtspMessage 消息持久化记录
     * @return 结果
     */
    @Override
    public int insertVtspMessage(VtspMessage vtspMessage)
    {
        vtspMessage.setCreateTime(DateUtils.getNowDate());
        return vtspMessageMapper.insertVtspMessage(vtspMessage);
    }

    /**
	 * 修改消息持久化记录
     * 
     * @param vtspMessage 消息持久化记录
     * @return 结果
     */
    @Override
    public int updateVtspMessage(VtspMessage vtspMessage)
    {
        vtspMessage.setUpdateTime(DateUtils.getNowDate());
        return vtspMessageMapper.updateVtspMessage(vtspMessage);
    }

    /**
	 * 删除消息持久化记录对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteVtspMessageByIds(String ids)
    {
        return vtspMessageMapper.deleteVtspMessageByIds(Convert.toStrArray(ids));
    }

    /**
	 * 删除消息持久化记录信息
     * 
     * @param messageId 消息持久化记录ID
     * @return 结果
     */
    @Override
    public int deleteVtspMessageById(Long messageId)
    {
        return vtspMessageMapper.deleteVtspMessageById(messageId);
    }


    /**
     * 信息持久化
     *
     * @param type  持久化的信息类型    0-志愿者申请，1-活动咨询，2-问题反馈，3-活动招募，4-活动邀请，5-活动报名，6-更新可视化模块消息
     * @param activityId    活动id
     * @param userId    消息的消费者
     */
    @Override
    public void sendMessage(int type, Long activityId, Long userId) {
        //志愿者消息推送对象
        JSONObject jo = new JSONObject();
        //消息持久化
        if (type != 6){
            //添加一条消息持久化记录
            VtspMessage vtspMessage = new VtspMessage();
            vtspMessage.setMessageType(type);
            vtspMessage.setMessageClassify(type);
            if (type == 0){
                //查询志愿者的通过与否状态
                VtspVolunteer vtspVolunteer = vtspVolunteerMapper.selectVtspVolunteerById(userId);
                //3-未通过，6-通过
                if (vtspVolunteer.getMemberState() == 3){
                    vtspMessage.setMessageContent("未通过志愿者申请");
                }else if (vtspVolunteer.getMemberState() == 6){
                    vtspMessage.setMessageContent("通过志愿者申请");
                }
            }else if (type == 1){
                //查询回复内容(传递的为咨询id)
                VtspAdvice vtspAdvice = vtspAdviceMapper.selectVtspAdviceById(activityId);
                vtspMessage.setMessageContent(vtspAdvice.getAdviceAnswer());
            }else if (type == 2){
                //查询反馈的应答内容(传递的为反馈id)
                VtspFeedback vtspFeedback = vtspFeedbackMapper.selectVtspFeedbackById(activityId);
                vtspMessage.setMessageContent(vtspFeedback.getFeedbackAnswer());
            }else if (type == 3){
                //查询活动名称
                VtspActivity vtspActivity = vtspActivityMapper.selectVtspActivityById(activityId);
                //活动招募
                vtspMessage.setMessageContent(String.format("%s%s",vtspActivity.getActivityName(),"开始招募志愿者"));
            }else if (type == 4){
                //查询活动名称
                VtspActivity vtspActivity = vtspActivityMapper.selectVtspActivityById(activityId);
                //活动邀请
                vtspMessage.setMessageContent(String.format("%s%s","华文教育者平台邀请您参加",vtspActivity.getActivityName()));
            }else if (type == 5){
                //查询报名信息(传递的是报名的id)
                VtspEnroll vtspEnroll = vtspEnrollMapper.selectVtspEnrollById(activityId);
                //查询活动名称
                VtspActivity vtspActivity = vtspActivityMapper.selectVtspActivityById(vtspEnroll.getActivityId());
                /*//创建一个报名对象，用来查询报名情况
                VtspEnroll vtspEnroll = new VtspEnroll();
                //设置查询条件
                vtspEnroll.setVolunteerId(userId);
                vtspEnroll.setActivityId(activityId);*/
                //查询活动报名的状态通过、未通过
//                VtspEnroll enroll = vtspEnrollMapper.selectVtspEnrollByUIdAndActivityId(vtspEnroll);
                if (vtspEnroll.getEnrollState() == 3){
                    vtspMessage.setMessageContent(String.format("%s%s",vtspActivity.getActivityName(),"报名未通过"));
                }else if (vtspEnroll.getEnrollState() == 6){
                    vtspMessage.setMessageContent(String.format("%s%s",vtspActivity.getActivityName(),"报名通过"));
                }
            }
            vtspMessage.setBizId(activityId);
            vtspMessage.setMessageUser(userId);
            vtspMessage.setState(0);
            vtspMessage.setCreateBy("xt");
            vtspMessage.setCreateTime(DateUtils.getNowDate());
            vtspMessageMapper.insertVtspMessage(vtspMessage);
        }
        //对产生变化时进行，发送变化通知 -6 志愿者信息，包括注册情况，年龄分布情况，注册分布情况
        if (type == 6){
            //查询各个学历的志愿者情况
            List<Map<String, Object>> volunteerDegreeVisual = vtspVisualMapper.getVolunteerDegreeVisual();
            //查询各个年龄段的志愿者情况
            List<Map<String, Object>> volunteerAgeVisual = vtspVisualMapper.getVolunteerAgeVisual();
            //查询每年注册的志愿者数
            List<Map<String, Object>> volunteerGrowthTrendVisual = vtspVisualMapper.getVolunteerGrowthTrendVisual();
            //查询各个国家的志愿者人数以及总服务时长
            List<Map<String, Object>> localList = vtspVisualMapper.getVolunteerAreaVisual();
            //volunteerAreaVisual用于存储各个国家及其对应的志愿者人数
            List<Map<String,Object>> volunteerAreaVisual = new ArrayList<>();

            for (int i=0;i<localList.size();i++)
            {
                //map用于各个国家的志愿者及其总服务时长
                Map<String, Object> map = new HashMap<String, Object>();
                //将国家id强制转换为整数类型
                Integer areasId = Integer.parseInt(String.valueOf(localList.get(i).get("areasId")));

                //将国家名称和志愿者人数添加到map中
                map.put("areaName",vtspVolunteerStatisticMapper.getCountryName(areasId));
                map.put("number",localList.get(i).get("number"));
                map.put("serveTime",localList.get(i).get("serveTime"));

                //将map添加到volunteerAreaVisual中
                volunteerAreaVisual.add(map);
            }

            //查询正式志愿者的总人数
            Integer volunteerSumVisual = vtspVisualMapper.getVolunteerSumVisual();
            //查询累计注册志愿者的总次数
            Integer volunteerRegisterNumberVisual = vtspVisualMapper.getVolunteerRegisterNumberVisual();
            //查询每月开展的活动次数
            List<Map<String, Object>> activityGrowthTrendVisual = vtspVisualMapper.getActivityGrowthTrendVisual();
            //查询各个活动类型的活动数
            List<Map<String, Object>> activityTypeVisual = vtspVisualMapper.getActivityTypeVisual();
            //查询近十二个月每个月累计的服务对象
            List<Map<String, Object>> serviceObjectVisual = vtspVisualMapper.getServiceObjectVisual();
            //查询累计开展活动的的总人数
            Integer activitySumVisual = vtspVisualMapper.getActivitySumVisual();

            //查询各个学院正式志愿者人数
            List<Map<String, Object>> volunteerCollegeDistribution = vtspVolunteerStatisticMapper.getVolunteerCollegeDistribution();
            //查询各个地区正式志愿者人数
            //volunteerLocalDistribution用于存储各个国家及其对应的志愿者人数
            List<Map<String,Object>> volunteerLocalDistribution = new ArrayList<>();

            for (int i=0;i<localList.size();i++)
            {
                //map用于存储一个国家的名称及其对应的志愿者人数
                Map<String, Object> map = new HashMap<String, Object>();
                //将国家id强制转换为整数类型
                Integer areasId = Integer.parseInt(String.valueOf(localList.get(i).get("areasId")));

                //将国家名称和志愿者人数添加到map中
                map.put("name",vtspVolunteerStatisticMapper.getCountryName(areasId));
                map.put("value",localList.get(i).get("number"));

                //将map添加到countryList中
                volunteerLocalDistribution.add(map);
            }
            //查询每年成为志愿者的人数
            List<Map<String, Object>> volunteerGrowthTrend = vtspVolunteerStatisticMapper.getVolunteerGrowthTrend();
            //查询志愿者黑名单人数
            Integer blacklist = vtspVolunteerStatisticMapper.getBlacklist();
            //查询应届生，往届生志愿者人数
            List<Map<String, Object>> allPreviousBirthDistribution = vtspVolunteerStatisticMapper.getAllPreviousBirthDistribution();

            //查询各个国家服务对象人数
            List<Map<String, Object>> serviceObjectLocalDistribution = vtspActivityStatisticMapper.getServiceObjectLocalDistribution();
            //查询各个活动状态的活动数
            List<Map<String, Object>> activityState = vtspActivityStatisticMapper.getActivityState();
            //查询每年开展的活动数
            List<Map<String, Object>> activityGrowthTrend = vtspActivityStatisticMapper.getActivityGrowthTrend();
            //查询每年服务对象人数
            List<Map<String, Object>> serviceObjectGrowthTrend = vtspActivityStatisticMapper.getServiceObjectGrowthTrend();
            //查询各个年龄段服务对象人数
            List<Map<String, Object>> serviceObjectAgeDistribution = vtspActivityStatisticMapper.getServiceObjectAgeDistribution();

            //放入数据，并转成json格式
            jo.put("各个学历志愿者", JSONObject.toJSONString(volunteerDegreeVisual));
            jo.put("各个年龄段志愿者",JSONObject.toJSONString(volunteerAgeVisual));
            jo.put("查询每年注册的志愿者数",JSONObject.toJSONString(volunteerGrowthTrendVisual));
            jo.put("查询各个国家的志愿者人数以及总服务时长",JSONObject.toJSONString(volunteerAreaVisual));
            jo.put("正式志愿者的总人数",volunteerSumVisual.toString());
            jo.put("注册志愿者的总次数",volunteerRegisterNumberVisual.toString());
            jo.put("每月开展的活动次数",JSONObject.toJSONString(activityGrowthTrendVisual));
            jo.put("各个活动类型的活动数",JSONObject.toJSONString(activityTypeVisual));
            jo.put("十二个月每个月累计的服务对象",JSONObject.toJSONString(serviceObjectVisual));
            jo.put("累计开展活动的的总人数",JSONObject.toJSONString(activitySumVisual));

            jo.put("各个学院志愿者人数",JSONObject.toJSONString(volunteerCollegeDistribution));
            jo.put("各个地区志愿者人数",JSONObject.toJSONString(volunteerLocalDistribution));
            jo.put("每年成为志愿者的人数",JSONObject.toJSONString(volunteerGrowthTrend));
            jo.put("黑名单志愿者人数",JSONObject.toJSONString(blacklist));
            jo.put("应届生，往届生志愿者人数",JSONObject.toJSONString(allPreviousBirthDistribution));

            jo.put("各个国家服务对象人数",JSONObject.toJSONString(serviceObjectLocalDistribution));
            jo.put("各个活动状态的活动数",JSONObject.toJSONString(activityState));
            jo.put("每年开展的活动数",JSONObject.toJSONString(activityGrowthTrend));
            jo.put("每年服务对象人数",JSONObject.toJSONString(serviceObjectGrowthTrend));
            jo.put("各个年龄段服务对象人数",JSONObject.toJSONString(serviceObjectAgeDistribution));

            //将数据解析出的多余的'/'，替换
            String data = jo.toString().replaceAll("\\\\", "");
            //推送数据
            try {
                //发送数据，同时传给连接的客户端的id
                WebSocketServlet.sendInfo(data,userId.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
